//
//  UpdateLogoController.m
//  NPS
//
//  Created by jadd on 15/11/5.
//  Copyright © 2015年 jadd. All rights reserved.
//

#import "UpdateLogoController.h"
@interface UpdateLogoController ()

@property (nonatomic,strong) UIImageView *image;
@end


@implementation UpdateLogoController
@synthesize myTableView;
@synthesize link;
@synthesize myWebView;

@synthesize _progressView;
@synthesize _progressProxy;

-(void) getViewInit
{
    CGRect rect;
    rect = CGRectMake(0, 0, self.view.bounds.size.width, 150);
    
    myTableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStyleGrouped];
    //右边滚动条是否显示
    [myTableView setShowsVerticalScrollIndicator:NO];
    myTableView.delaysContentTouches = NO;
    myTableView.scrollEnabled = NO;
    myTableView.delegate = self;
    myTableView.dataSource = self;
    //UITableView 去除空的Cell
    myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, 45.0f)];
    footView.backgroundColor = CLEAR;
  
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, footView.size.width, footView.size.height)];
    lable.textColor = GRAY;
    lable.adjustsFontSizeToFitWidth = YES;
    lable.font = [UIFont systemFontOfSize:15];
    lable.text = @"企业Logo将出现在问卷网的左上方，效果如下";
    [footView addSubview:lable];
    [myTableView setTableFooterView:footView];
    [self.view addSubview:myTableView];
}

-(void) setWebView
{
    CGRect rect = CGRectMake(0, 155, K_ScreenWidth, K_ScreenHeight-64-155);
    myWebView = [[UIWebView alloc] initWithFrame:rect];
    myWebView.delegate = self;
    
    myWebView.scalesPageToFit = YES;//按比例适配屏幕
    [myWebView  setUserInteractionEnabled: YES ];  //是否支持交互
    myWebView.keyboardDisplayRequiresUserAction = YES;//交互时显示键盘
    
//    _progressProxy = [[NJKWebViewProgress alloc] init];
//    myWebView.delegate = _progressProxy;
//    _progressProxy.webViewProxyDelegate = self;
//    _progressProxy.progressDelegate = self;
//    
//    CGFloat progressBarHeight = 2.f;
//    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
//    CGRect barFrame = CGRectMake(0, 0, navigationBarBounds.size.width, progressBarHeight);
//    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
//    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    NSLog(@"%@",self.link);
    NSURLRequest *request = [NSURLRequest requestWithURL:self.link]; // 定义请求地址
    [myWebView loadRequest:request];
    //[self.view addSubview:myWebView];
}

-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    
    self.title = @"更换logo";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = BACK_VIEW_COLOR;
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    button.frame = CGRectMake(0, 0, K_Global_BackButton_Width, K_Global_BackButton_Height);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateNormal];
    //[button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;

    [self getViewInit];
    [self setWebView];

    [super viewDidLoad];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


-(void) viewWillAppear:(BOOL)animated
{
    
    //[myWebView addSubview:_progressView];
    [super viewWillAppear:YES];
}


-(void) viewWillDisappear:(BOOL)animated
{
    //[_progressView removeFromSuperview];
    [super viewWillDisappear:YES];
}

-(void) viewDidDisappear:(BOOL)animated
{
    [Config hideActivityView];
    [super viewDidDisappear:animated];
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 55;
}



-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //NSLog(@"%f",K_ScreenHeight - 100);
    if(section == 0)
        return 0 ;
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *identifier = @"TJCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    
    CGRect rect = CGRectMake((K_ScreenWidth/320)*145, 10, 150, 35);
    //[self.image setFrame:rect];
    
    self.image = [[UIImageView alloc] init];
    //[self.image setBackgroundColor:RED];
    [self.image setFrame:rect];
    
    self.image.userInteractionEnabled = YES;

    NSString *path = [[NSUserDefaults standardUserDefaults] objectForKey:UserDefault_logo];
    
    [self.image setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"dianpu"]];
    
    self.image.clipsToBounds = YES;
    self.image.contentMode =  UIViewContentModeScaleAspectFit;
    //self.image.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    [cell.contentView addSubview:self.image];
    
    
    cell.textLabel.text = @"企业Logo";
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}


#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        [self chooseImagePressed];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)chooseImagePressed {
    UIActionSheet *sheet;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取 消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取",@"拍照", nil];
    } else {
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取 消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取", nil];
    }
    sheet.tag = 255;
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 255) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            switch(buttonIndex)
            {
                case 2://取消
                    return;
                case 1://相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 0: //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                default:
                    return;
            }
        }
        else
        {
            if(buttonIndex == 1){
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSData *data;
    
    if (UIImagePNGRepresentation(image) == nil)
    {
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    else
    {
        data = UIImagePNGRepresentation(image);
    }
    
    
//    //存入沙盒
//    NSString *path_sandox = NSHomeDirectory();
//    //设置一个图片的存储路径
//    NSString *imagePath = [path_sandox stringByAppendingString:@"/Documents/changeLogo.png"];
//    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
//    [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    
    
    [self uploadImage:data Image:image];
    
    
}

-(void) uploadImage:(NSData *) imageData Image:(UIImage *)image
{
    [Config showActivityView];
    [myWebView removeFromSuperview];
    
    
    ChangeLogoRequest * request = [[ChangeLogoRequest alloc] initWithUserId:[Config getUser_id]];
    [RequestHandle uplaodImageOperationWithRequest:request uploadData:imageData complete:^(id responseObject) {
        
        ChangeLogoResponse * response = [[ChangeLogoResponse alloc] init];
        response.responseObject = responseObject;
        
        if([[responseObject objectForKey:@"status"] isEqualToString:@"success"])
        {
           
            //NSString *path = [self getImagePath];
            [self.image setImage:image];
            //[Config showMessage:@"更换成功"];
            //[self.image setImageWithURL:[MyGlobal sharedVariables].logoUrl];

            
            dispatch_async(dispatch_get_main_queue(), ^{
                [NSThread sleepForTimeInterval:3];
                //[myWebView reload];
               
                NSURLRequest *request = [NSURLRequest requestWithURL:self.link]; // 定义请求地址
                [myWebView loadRequest:request];
                
            });
            
            [Config hideActivityView];

        }
        while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
        
    
    } error:^(NSError *error) {
        //NSLog(@"%@",error);
        if(error.code == ERROR_PARA_VERIFIY){
            RepeatLoginController *controller = [[RepeatLoginController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
            controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:nav animated:YES completion:^{
                NSLog(@"");
            }];
        }
        else{
            [Config showMessage:error.localizedDescription];
        }
    }];
    
}

//几个代理方法

- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    NSLog(@"webViewDidStartLoad");
    
    [Config showActivityView];
    [self.view addSubview:myWebView];
    
}

- (void)webViewDidFinishLoad:(UIWebView *)web{
    
    NSLog(@"webViewDidFinishLoad");
    [Config hideActivityView];
    
}

-(void)webView:(UIWebView*)webView  DidFailLoadWithError:(NSError*)error{
    
    NSLog(@"DidFailLoadWithError");
    
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    //self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

-(NSString *)getImagePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",path,@"changeLogo.png"];
    return imagePath;
}
@end
